<?php


namespace app\controller\backend;


use app\exception\ModelEmptyException;
use app\exception\ModelException;
use app\model\Link;
use app\model\LinkWebsite;
use app\model\Model;
use app\model\RecycleBin;
use app\validate\LinkValidate;
use think\facade\Db;
use think\response\Json;

class LinkController extends BaseController
{
    /**
     * 友情链接列表
     * @key id， seller_id
     * @return Json
     * @throws \app\exception\ModelException
     */
    public function index(Link $link): Json
    {
        if(request()->isGet()) {
            $param = input('get.');
            $param['seller_id'] = $this->admin['seller_id'];
            try {
                validate(LinkValidate::class)->scene('index')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $where = [
                'website_id'  => $param['website_id'],
                'seller_id' => $param['seller_id'],
                'type' => $param['type'],
                'is_del' => 1
            ];
            $limit = $this->setLimit();
            // 翻页数据
            $res = $link->getLinkList($where,$limit);
            $data = pageReturn($res);

            // 统计数据
            $total = $data['count'];
            $changeNum = 0;
            if($total){
                $now = mktime(0,0,0,date('m'),1,date('Y'));
                // 上月总数
                $lastMonthNum = $link->where($where)->whereTime('create_time','<',$now)->count();
                $changeNum = $total - $lastMonthNum;
            }
            $data['change'] = $changeNum;
            return json($data);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 读取单条友情链接信息
     * @return Json
     */

    public function read(Link $link): Json
    {
        if (request()->isGet()) {
            $param = input('get.');
            $param['seller_id'] = $this->admin['seller_id'];
            try {
                validate(LinkValidate::class)->scene('read')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $param['is_del'] = 1;
            $res = $link->getLink($param);
            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 新增友情链接
     * @return Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Link $link): Json
    {
        if(request()->isPost()) {
            $param = input('post.');
            $param['seller_id'] = $this->admin['seller_id'];

            try {
                validate(LinkValidate::class)->scene('save')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            if(isset($param['add_time']) && empty($param['add_time'])){
                unset($param['add_time']);
            }
            if(isset($param['end_time']) && empty($param['end_time'])){
                unset($param['end_time']);
            }
            $link->saveUnique(['seller_id'=>$param['seller_id'],'website_id'=>$param['website_id'],'type'=>$param['type'],'name'=>$param['name'],'is_del'=>1],'友情链接已经存在');
            $res = $link->addLink($param);
            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 更新友情链接信息
     * @return Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function update(Link $link): Json
    {
        if (request()->isPost())
        {
            $param = input('post.');

            try {
                validate(LinkValidate::class)->scene('update')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $param['website_id'],
            ];
            if(isset($param['add_time']) && empty($param['add_time'])){
                unset($param['add_time']);
            }
            if(isset($param['end_time']) && empty($param['end_time'])){
                unset($param['end_time']);
            }
            $link->updateUnique([
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $param['website_id'],
                'type' => $param['type'],
                'name' => $param['name'],
            ],$param['id'],'友情链接名称已存在');
            $link->updateUnique([
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $param['website_id'],
                'type' => $param['type'],
                'url' => $param['url'],
            ],$param['id'],'友情链接地址已存在');
            $res = $link->updateLink($where,$param);

            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 删除友情链接信息
     * @return Json
     * @throws ModelException
     */
    public function delete(Link $link,RecycleBin $recycleBin): Json
    {
        if (!request()->isPost()) {
            return jsonReturn(-2, '请求方法错误');
        }
        $param = input('post.');
        try {
            validate(LinkValidate::class)->scene('read')->check($param);
        } catch (\Exception $e) {
            return jsonReturn(-4, $e->getMessage());
        }
        $param['seller_id'] = $this->admin['seller_id'];
        $where = [
            'id' => $param['id'],
            'seller_id'     => $param['seller_id'],
            'website_id'    => $param['website_id'],
            'is_del'    => 1,
        ];
        Db::startTrans();
        try{
            $res = $link->softDelLink($where);
            if($res['data'] == 1){
                $binData = [
                    'object_id' => $param['id'],
                    'table_name'   => 'link',
                    'title' => "友情链接{$param['id']}",
                    'admin_id'  => $this->admin['uid'],
                    'name'  => $this->admin['name'],
                ];
                $recycleBin->addRecycleBin($binData);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return jsonReturn(-3,$e->getMessage());
        }
        return json($res);

    }

    /**
     * @throws ModelException
     */
    public function copy(Link $link): Json
    {
        if(!request()->isPost()){
            return jsonReturn(-1, '请求方式错误');
        }
        $param = input('post.');
        try {
            validate(LinkValidate::class)->scene('copy')->check($param);
        } catch (\Exception $e) {
            return jsonReturn(-4, $e->getMessage());
        }
        if($param['website_id'] == $param['copy_site_id']){
            return jsonReturn(-5, '目标网站ID和复制网站ID不能相等');
        }
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'website_id' => $param['copy_site_id'],
            'is_del'    => 1,
        ];
        $selfWhere = [
            'seller_id' => $this->admin['seller_id'],
            'website_id' => $param['website_id'],
            'is_del'    => 1,
        ];
        $field = ['name','url','sort','target','is_del'];
        $linkList = $link->getAllLink($where,$field)['data']->toArray();
        $selfList = $link->getAllLink($selfWhere,$field)['data']->toArray();
        $flag = array_column($selfList,'name');
        if(!empty($linkList)){
            foreach($linkList as $key => &$val){
                $val['website_id'] = $param['website_id'];
                if(in_array($val['name'],$flag)){
                    unset($linkList[$key]);
                }
            }
            unset($val);
            $res = json($link->addAllLink($linkList));
        }else{
            $res = jsonReturn(0,0,'success');
        }
        return $res;
    }
}